//axios二次封装
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'

import cache, { CacheType } from '@/utils/cache'

// 使用loading加载
import { ElLoading } from 'element-plus'

// 默认接口数据请求类型
export interface AxiosDefaultTypes<T> {
  code: number
  mes: string
  data?: T
}

let loading: any

interface Options {
  lock: boolean
  text: string
  background: string
}

// 显示加载动画
const startLoading = (): void => {
  const options: Options = {
    lock: true,
    text: 'Loading...',
    background: 'rgba(255,255,255,0.7)'
  }
  loading = ElLoading.service(options)
}

// 关闭加载动画
const endLoading = (): void => {
  loading.close()
}

// export const baseURL: string =
//   process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : ''

export const baseURL: string =
  process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : ''

export const axiosdefaultUrl: string =
  process.env.NODE_ENV === 'development' ? '/api' : ''

axios.defaults.baseURL = axiosdefaultUrl as string
axios.defaults.withCredentials = true as boolean

// 添加请求拦截器
// 在发送请求之前做些什么
axios.interceptors.request.use((config: AxiosRequestConfig) => {
  // 开启loading加载动画
  startLoading()
  const token: string | null = cache.getItem('token', CacheType.session)
  if (!config.headers) return
  // 添加token
  config.headers.Authorization = 'Bearer ' + token
  return config
})
// 添加响应拦截器
axios.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    // 对响应数据做点什么
    // 关闭loading加载动画
    endLoading()
    return response
  },
  (err) => {
    // 对响应错误做点什么
    // 关闭loading加载动画
    endLoading()
    return Promise.reject(err)
  }
)

export default axios
